package com.doule.farmerassistant;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;

import com.doule.farmerassistant.ToolHelper.HttpError;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
    /**
     * The default email to populate the email field with.
     */
    public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    /**
     * Login account.
     */
    private String mAccount;

    /**
     * Login password.
     */
    private String mPassword;

    /**
     * 
     */
    private String mACCOUNT = "ACCOUNT";

    /**
     * Account View.
     */
    private EditText mAccountView;

    /**
     * Password View.
     */
    private EditText mPasswordView;

    /**
     * Login form view.
     */
    private View mLoginFormView;

    /**
     * Login status view.
     */
    private View mLoginStatusView;

    /**
     * Login status message view.
     */
    private TextView mLoginStatusMessageView;

    /**
     * Check box.
     */
    private CheckBox mCheckBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        mAccount = getIntent().getStringExtra(EXTRA_EMAIL);
        mAccountView = (EditText) findViewById(R.id.account);
        mCheckBox = (CheckBox) findViewById(R.id.cb_remember_account);
        mAccountView.setText(mAccount);

        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView
                .setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView textView, int id,
                            KeyEvent keyEvent) {
                        if (id == R.id.login || id == EditorInfo.IME_NULL) {
                            attemptLogin();
                            return true;
                        }
                        return false;
                    }
                });

        mLoginFormView = findViewById(R.id.login_form);
        mLoginStatusView = findViewById(R.id.login_status);
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

        findViewById(R.id.sign_in_button).setOnClickListener(onClickListener);
        loadAccAndPass();
    }

    /**
     * On click listener.
     */
    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
            case R.id.sign_in_button:
                attemptLogin();
                break;
            default:
                break;
            }
        }

    };

    /**
     * Save account and password.
     * 
     * @param acc
     *            Account.
     * @param pass
     *            Password.
     */
    private void saveAccAndPass(final String acc, final String pass) {
        SharedPreferences share = getSharedPreferences(mACCOUNT, MODE_PRIVATE);
        SharedPreferences.Editor edit = share.edit();
        edit.putString("account", acc);
        edit.putString("password", pass);
        edit.commit();
    }

    /**
     * Load account and password.
     */
    private void loadAccAndPass() {
        SharedPreferences share = getSharedPreferences(mACCOUNT, MODE_PRIVATE);
        mAccountView.setText(share.getString("account", ""));
        mPasswordView.setText(share.getString("password", ""));
        if (mAccountView.getText().toString() != null
                && !mAccountView.getText().toString().equals("")) {
            mCheckBox.setChecked(true);
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mAccountView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        mAccount = mAccountView.getText().toString();
        mPassword = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password.
        if (TextUtils.isEmpty(mPassword)) {
            mPasswordView.setError(getString(R.string.error_field_required));
            focusView = mPasswordView;
            cancel = true;
        } else if (mPassword.length() < 4) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(mAccount)) {
            mAccountView.setError(getString(R.string.error_field_required));
            focusView = mAccountView;
            cancel = true;
        }
        // else if (!mAccount.contains("@")) {
        // mAccountView.setError(getString(R.string.error_invalid_email));
        // focusView = mAccountView;
        // cancel = true;
        // }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
            showProgress(true);
            mAuthTask = new UserLoginTask();
            mAuthTask.execute((Void) null);
        }
    }

    /**
     * Shows the progress UI and hides the login form.
     * 
     * @param show
     *            show or hides login form
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        float loginStatusAlpha = 0;
        float loginFormAlpha = 1;
        if (show) {
            loginStatusAlpha = 1;
            loginFormAlpha = 0;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(
                    android.R.integer.config_shortAnimTime);

            mLoginStatusView.setVisibility(View.VISIBLE);
            mLoginStatusView.animate().setDuration(shortAnimTime)
                    .alpha(loginStatusAlpha)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            if (show) {
                                mLoginStatusView.setVisibility(View.VISIBLE);
                            } else {
                                mLoginStatusView.setVisibility(View.GONE);
                            }
                        }
                    });

            mLoginFormView.setVisibility(View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime)
                    .alpha(loginFormAlpha)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            if (show) {
                                mLoginFormView.setVisibility(View.GONE);
                            } else {
                                mLoginFormView.setVisibility(View.VISIBLE);
                            }
                        }
                    });
        } else {
            if (show) {
                mLoginStatusView.setVisibility(View.VISIBLE);
                mLoginFormView.setVisibility(View.GONE);
            } else {
                mLoginStatusView.setVisibility(View.GONE);
                mLoginFormView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * Start Service.
     */
    private void startService() {
        Intent intent = new Intent(this, MyService.class);
        intent.putExtra("account", mAccount);
        intent.putExtra("password", mPassword);
        
        if (startService(intent) == null) {
            Log.e("LoginActivity", "start LanService failed");
        } else {
            Log.e("LoginActivity", "start LanService succeed ");
        }
    }
    
    /**
     * Start task ListActivity.
     * @param token token
     */
    private void startMainActivity(final String token) {
        Intent intent = new Intent();
        intent.setClass(this, MainActivity.class);
        intent.putExtra("tk", token);
        startActivity(intent);
    }
    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
        /**
         * authentication token.
         */
        private String token;

        /**
         * error.
         */
        private ToolHelper.HttpError error;
        
        /**
         * Http request to login.
         * 
         * @return true if login success, else false.
         */
        private boolean login() {
            String serverUrl = DeathConfig.getServerUrl();
            if (serverUrl == null || serverUrl.equals("")) {
                error = new ToolHelper.HttpError(0, "please setting server url !");
                return false;
            }
            
            Log.e("UserLoginTask", "serverUrl: " + serverUrl);
            String account = mAccountView.getText().toString();
            String password = mPasswordView.getText().toString();
            Log.e("UserLoginTask", "account: " + account + ", password: "
                    + password);
            HttpPost request = new HttpPost(serverUrl + "/login");
            request.setHeader("content-type", "application/octet-stream");
            request.setHeader("account", account);
            request.setHeader("password", password);

            AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
            try {
                HttpResponse resp = client.execute(request);
                error = ToolHelper.errorParse(LoginActivity.this, resp);
                if (error != null) {
                    return false;
                }
                
                Header header1 = resp.getFirstHeader("tk");
                token = header1.getValue();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                error = new ToolHelper.HttpError(0, "http connection failed");
            } finally {
                client.close();
            }
            return false;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            if (login()) {
                return true;
            }

            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                if (mCheckBox.isChecked()) {
                    saveAccAndPass(mAccount, mPassword);
                }
                // DeathConfig.putPref("tk", token, LoginActivity.this);
                LoginActivity.this.startService();
                LoginActivity.this.startMainActivity(token);
                
                finish();
            } else {
                if (error != null) {
                    mPasswordView.setError(error.getMsg());
                    mPasswordView.requestFocus();
                }
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}
